<template>
  <div>
    <el-upload
      :action="url"
      :before-upload="beforeAvatarUpload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-error="handleUploadFail"
      :on-success="handleUploadSuccess"
      :on-exceed="handleExceed"
      :limit="4"
      :file-list="fileList"
      name="files"
      :with-credentials="true"
      :headers="headersData"
      >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">上传文件，且不超过10M</div>
    </el-upload>
    <el-dialog title="PDF预览" width="45%" :visible.sync="dialogPdfVisible" append-to-body :before-close="closePdf" class="dialog_style" >
      <pdf v-if="fileType" width="100%" style="width:100%" :page="currentPage" @num-pages="pageCount=$event" @page-loaded="currentPage=$event" :src="baseUrl+'/file/'+ pdfCopy +'?token=' + token"></pdf>
      <div v-if="!fileType" class="ylImg">
          <el-image
            style="width: 100%"
            :src="baseUrl+'/file/'+ pdfCopy +'?token=' + token"
            fit="fill"></el-image>
      </div>
      <el-pagination v-if="fileType" background
          @current-change="handlePdfpage"
          :current-page.sync="currentPage"
          layout="total, prev, pager, next, jumper"
          :page-size="1"
          :total="pageCount">
       </el-pagination>
    </el-dialog>
  </div>
</template>
<style scoped>
</style>

<script>
import {getToken} from '@/utils/LocalDataUtil'
import config from '@/config/index'
import pdf from 'vue-pdf'
export default {
  model: {
    prop: 'imgUrl',
    event: 'updateImgUrl'
  },
  props: {
    imgUrl: {
      type: Array,
      default () {
        return []
      }
    },
    type: {
      type: String,
      default () {
        return ''
      }
    }
  },
  data () {
    return {
      fileList: [],
      headersData: {},
      url: '',
      pdfCopy: '',
      pageCount: 0, // pdf 总页码
      currentPage: 0, // pdf 当前页码
      name: [],
      tempUrl: [],
      token: getToken(),
      baseUrl: config.serverUrl(),
      flag: true,
      fileType: true,
      dialogPdfVisible: false
    }
  },
  components: {pdf},
  mounted () {
    this.init()
  },
  methods: {
    init () {
      this.url = config.serverUrl() + '/file/'
      this.headersData.token = getToken()
    },
    beforeAvatarUpload (file) {
      this.flag = false
      const isJPG = file.type.indexOf('mp4') < 0 && file.type.indexOf('rmvb') < 0 && file.type.indexOf('avi') < 0 && file.type.indexOf('ts')
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isJPG) {
        this.$message.error('附件不能上传视频')
      }
      if (!isLt2M) {
        this.$message.error('文件大小不能大于10M')
      }
      return isJPG && isLt2M
    },
    handleRemove (file, fileList) {
      var obj = {}
      obj.file = file
      obj.type = this.type
      this.$emit('updateImgUrl', fileList)
      this.$emit('delImgUrl', obj)
    },
    handlePreview (file) {
      this.dialogPdfVisible = true
      if (file.name.indexOf('pdf') !== -1) {
        this.fileType = true
        this.pdfCopy = file.url
      } else if ((file.name.indexOf('jpg') !== -1) || (file.name.indexOf('png') !== -1)) {
        this.fileType = false
        this.pdfCopy = file.url
      } else {
        this.dialogPdfVisible = false
        window.location.href = this.url + file.url + '?token=' + this.token
      }
    },
    handleUploadSuccess (response, file, fileList) {
      if (response && response.code === '200' && response.data) {
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].response) fileList[i].url = fileList[i].response.data[0]
        }
        this.$emit('updateImgUrl', fileList)
      } else {
        let message = `上传失败，原因：` + response.message
        this.$message.error(message)
      }
    },
    handleUploadFail (err, file, fileList) {
      console.log(err)
      console.log(file)
      console.log(fileList)
    },
    handleExceed (files, fileList) {
      this.$message.error('只能上传四张图片!')
    },
    clearFileList () { // 初始化fileList
      this.fileList = []
    },
    buildUri (path) {
      if (path && path !== '') {
        return this.url + path
      }
      return null
    },
    handlePdfpage (val) {
      this.currentPage = val
    },
    closePdf (type) {
      this.dialogPdfVisible = false
    }
  },
  watch: {
    imgUrl: {
      handler: function (newValue, oldValue) {
        this.fileList = this.imgUrl
      },
      deep: true
    }
  }
}
</script>
